package com.ruoyi.business.config;

import com.alibaba.fastjson.JSON;

import com.ruoyi.business.entity.ChatContent;
import com.ruoyi.business.service.FrontChatContentService;
import com.ruoyi.business.utils.DateTimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.*;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
@EnableWebSocket
class WebSocketConfig implements WebSocketConfigurer {

    private Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    //数据持久化对象
    @Autowired
    private FrontChatContentService frontChatContentService;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new MyWebSocketHandler(), "/chat")
                .addInterceptors(new MyHandshakeInterceptor())
                .setAllowedOrigins("*");
    }

    //内部类实现聊天

    private class MyHandshakeInterceptor implements HandshakeInterceptor {

        @Override
        public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
            // 在这里获取客户端传递的账号信息
            String account = request.getURI().getQuery(); // 从URL中获取账号信息，例如 "account=your_account"
            //获取参数
            String[] queryParams = account.split("="); // 将查询参数拆分成数组
            String userid = queryParams[1];  //获取的用户编号：123456seller
            attributes.put("userid", userid); // 将账号信息放入WebSocket会话的属性中
            return true;
        }

        @Override
        public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
            // 这里可以添加一些处理逻辑，如果需要的话
        }
    }

    private class MyWebSocketHandler implements WebSocketHandler {

        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            System.out.println("WebSocket connected: " + session.getId());

            //获取账号
            String userid = (String) session.getAttributes().get("userid");
            //将会话存储到集合中
            sessions.put(userid,session);

        }

        //收到消息之后的处理
        @Override
        public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
            //获取收到的消息字符串
            String messagePayload = message.getPayload().toString();
            System.out.println(message);
            System.out.println("Received message from " + session.getId() + ": " + messagePayload);
            
            //将消息字符串转成对应的消息对象

            // 将消息发送给对应的用户
            ChatContent chatContent = JSON.parseObject(messagePayload, ChatContent.class);
            if(chatContent==null){
                return;
            }
            
            //补充发送信息
            chatContent.setSendTime(DateTimeUtils.getCurrentLocalDateTime());
            chatContent.setIsread(0);  //初始化为未读
            
            //进行数据持久化
            boolean save = frontChatContentService.save(chatContent);

            if(!save){  //持久化失败
                return;
            }

            //将数据发送给指定的对象

            //获取信息接收对象的sesion
            WebSocketSession receiveSession = sessions.get(chatContent.getReceiverUserid() + chatContent.getReceiverType());

            if(receiveSession==null){  //接收对象不在线
                return;

            }

            //接收对象在线,发送消息
            receiveSession.sendMessage(new TextMessage(JSON.toJSONString(chatContent)));

        }

        //错误处理
        @Override
        public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
            System.out.println("WebSocket error: " + exception.getMessage());
        }

        //断开连接处理,将session对象移除集合
        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {

            // 获取断开连接的用户的userid
            String userid = (String) session.getAttributes().get("userid");
            System.out.println("WebSocket disconnected userid: " + userid);
            // 从集合中移除对应的session
            sessions.remove(userid);
        }

        @Override
        public boolean supportsPartialMessages() {
            return false;
        }
    }
}